<template>
  <div class="container">
    <el-row :gutter="12">
      <el-col :span="14">
        <el-row :gutter="12">
          <el-col :span="12">
            <el-card shadow="hover">
              <el-descriptions style="height: 280px" class="margin-top" title="个人信息" :column="3"
                               direction="vertical">
                <template slot="extra">
                  <el-button type="text" @click="dialogFormVisible = true" size="small">修改</el-button>
                </template>
                <el-descriptions-item label="账号">{{ userInfo.userAccount }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ userInfo.userName }}</el-descriptions-item>
                <el-descriptions-item label="籍贯">{{ userInfo.userPlace }}</el-descriptions-item>
                <el-descriptions-item label="生日">{{ userInfo.userBirth }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userInfo.userTel }}</el-descriptions-item>
                <el-descriptions-item label="电子邮箱">{{ userInfo.userEmail }}</el-descriptions-item>
                <el-descriptions-item label="身份">
                  <el-tag size="small">{{ userInfo.userType == 0 ? '超级管理员' : '仓库管理员' }}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover">
              <div id="financial">
                <label>各年收支情况</label>
                <template>
                  <el-select size="mini" style="float: right;" v-model="financialType" placeholder="请选择"
                             @change="financialInfoEchartsChange(financialType)">
                    <el-option
                      v-for="item in financialOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </template>
                <div style="height: 250px" id="financial_info"/>
                <label style="float: right;padding-bottom: 14px">总收入:{{ this.income }}亿元</label>
              </div>
            </el-card>
          </el-col>

        </el-row>
        <el-row>
          <el-card shadow="hover">
            <div id="record">
              <label>出入库情况</label>
              <template>
                <el-select size="mini" style="float: right" v-model="recordType" placeholder="请选择"
                           @change="recordInOutEchartsInit(recordType)">
                  <el-option
                    v-for="item in recordOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </template>
              <div style="height: 400px" id="record_in_out"/>
            </div>
          </el-card>
        </el-row>
      </el-col>
      <el-col :span="10">
        <el-row>
          <el-card shadow="hover">
            <label>当前仓库状态</label>
            <div style="height: 360px" id="inventory"/>
          </el-card>
        </el-row>
        <el-row>
          <el-card shadow="hover">
            <div id="goods_sells_info">
              <label>近期热供榜</label>
              <el-table
                ref="singleTable"
                :data="tableData"
                stripe
                highlight-current-row
                @current-change="handleCurrentChange"
                style="width: 100%;padding-top: 38px">
                <el-table-column
                  type="index"
                  width="50">
                </el-table-column>
                <el-table-column
                  property="goodsName"
                  v-model="this.tableData.goodsName"
                  label="货物名称"
                  width="300">
                </el-table-column>
                <el-table-column
                  property="outCount"
                  v-model="this.tableData.outCount"
                  label="出库数量"
                  width="200"
                  :formatter="sellsFormatter">
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-row>
      </el-col>
    </el-row>
    <!-- Form -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      width="30%"
      center>
      <el-form
        :model="form">
        <el-form-item
          :label-width="formLabelWidth">
          <label>密码：</label>
          <el-input
            size="mini"
            type="password"
            style="width: 200px"
            v-model="form.password"
            autocomplete="off"
            show-password>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="edit">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import echarts from 'echarts'
import moment from 'moment'
import {
  getWarehouseStatusInfo,
  getRecordInOutInfos,
  getFinancialInfo,
  getGoodsSellsInfo,
  getFinancialType,
  checkPassword
} from '@/api/user'
import user_ from '@/store/modules/user'

Date.prototype.Format = function (fmt) {undefined
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export default {
  data() {
    return {
      dialogFormVisible: false,
      form: {
        password: '',
      },
      formLabelWidth: '120px',
      userInfo: {},
      financialOption: [],
      financialType: '',
      recordOptions: [{
        value: 'recent_day_total',
        label: '过去七天'
      }, {
        value: 'recent_month_total',
        label: '过去七月'
      }, {
        value: 'recent_year_total',
        label: '过去七年'
      }],
      recordType: 'recent_day_total',
      tableData: [],
      income: '10101',
      inventroy: {
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            var amount = params[0].data + params[1].data
            var rate = params[0].data / amount
            var res = '<div><span>容量：</span>' + amount + '</div>' + '<div><span>已用：</span>' + params[0].data + '</div>' + '<div><span>比率：</span>' + rate.toFixed(2) + '%</div>'
            return res
          }
        },
        xAxis: {
          data: []
        },
        yAxis: {},
        series: [
          {
            data: [],
            itemStyle: {
              color: '#5C7BD9',
            },
            type: 'bar',
            stack: '仓库'
          },
          {
            data: [],
            itemStyle: {
              color: '#E3E3E3',
            },
            type: 'bar',
            stack: '仓库'
          }
        ]
      },
      financial_info: {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return params.value + '亿元' + "(" + params.percent + "%)"
          }
        },
        series: [
          {
            type: 'pie',
            data: [],
          }
        ]
      },
      record_in_out: {
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            var res = '<div><span>入库数量：</span>' + (params[0].data / 10000.0).toFixed(2) + '万</div>' + '<div><span>出库数量：</span>' + (params[1].data / 10000.0).toFixed(2) + '万</div>'
            return res
          }
        },
        xAxis: {
          data: []
        },
        yAxis: {
          type: 'value',
          // 科学记数法
          axisLabel: {
            formatter: function (value) {
              if (Math.abs(value) > 100000) {
                if (value == 0) {
                  return "0";
                  // 检查是否已经转化为科学计数了
                } else if ((value + '').indexOf('e') > 0) {
                  return (value + '').replace(/e/, "E");
                } else {
                  var res = value.toString();
                  var numN1 = 0;
                  var numN2 = 1;
                  var num1 = 0;
                  var num2 = 0;
                  var t1 = 1;
                  // 计入小数点前后有多少位
                  for (var k = 0; k < res.length; k++) {
                    if (res[k] == ".")
                      t1 = 0;
                    if (t1)
                      num1++;
                    else
                      num2++;
                  }
                  // 均转换为科学计数法表示
                  if (Math.abs(value) < 1) {
                    // 小数点后一位开始计算
                    for (var i = 2; i < res.length; i++) {
                      if (res[i] == "0") {
                        numN2++; //记录10的负指数值（默认值从1开始）
                      } else if (res[i] == ".")
                        continue;
                      else
                        break;
                    }
                    var v = parseFloat(value);
                    // 10的numN2次方
                    v = v * Math.pow(10, numN2);
                    v = v.toFixed(1); //四舍五入 仅保留一位小数位数
                    return v.toString() + "e-" + numN2;
                  } else if (num1 > 1) {
                    numN1 = num1 - 1;
                    var v = parseFloat(value);
                    v = v / Math.pow(10, numN1);
                    if (num2 > 1) {
                      v = v.toFixed(1);
                    }
                    return v.toString() + "×10^" + numN1;
                  }
                }
              } else {
                return value;
              }
            }
          }
        },
        series: [
          {
            data: [],
            type: 'line',
          },
          {
            data: [],
            type: 'line',
          }
        ]
      }
    }
  },
  mounted() {
    this.inventoryEchartsInit()
    this.recordInOutEchartsInit(this.recordType)
    this.financialInfoEchartsInit()
  },
  created() {
    this.getGoodsSellsInfoList()
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.userInfo.userBirth = this.dateFormat(this.userInfo.userBirth)
  },
  methods: {
    dateFormat(date){
      return moment(date).format("YYYY年MM月DD日")
    },
    edit() {
      var info = {
        userAccount: this.userInfo.userAccount,
        userPasswd: this.form.password
      }
      checkPassword(info).then(res=>{
        if (res.data == null) {
          this.$message({
            message: '密码错误，请重试！',
            type: 'error'
          })
          this.form.password = ''
        } else {
          this.userInfo = res.data
          this.$router.push({name: 'UserEdit', params:{userId: this.userInfo.userId, password: this.form.password}})
        }
      })
    },
    financialInfoEchartsChange(year) {
      getFinancialInfo({recordYear: year}).then(res => {
        var parts = []
        parts[0] = {value: (res.data.benefit / 100000000.0).toFixed(2), name: '利润', itemStyle: {color: '#00b33c'}}
        parts[1] = {value: (res.data.outcome / 100000000.0).toFixed(2), name: '支出', itemStyle: {color: '#ff1a1a'}}

        console.log(parts)

        this.financial_info.series[0].data = parts

        this.income = (res.data.income / 100000000.0).toFixed(2)

        echarts.init(document.getElementById('financial_info')).setOption(this.financial_info)
      })
    },
    sellsFormatter(row, column) {
      return (row.outCount / 10000.0).toFixed(2) + '万'
    },
    getGoodsSellsInfoList() {
      getGoodsSellsInfo().then(res => {
        this.tableData = res.data
      })
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    inventoryEchartsInit() {
      getWarehouseStatusInfo().then(res => {
        this.inventroy.xAxis.data = res.data.warehouseNames
        this.inventroy.series[0].data = res.data.busy
        this.inventroy.series[1].data = res.data.frees
        echarts.init(document.getElementById('inventory')).setOption(this.inventroy)
      })
    },
    financialInfoEchartsInit() {
      getFinancialType().then(res => {
        var list = res.data
        this.financialType = list[list.length - 1]
        console.log(list)

        for (var i = 0; i < list.length; i++) {
          this.financialOption[i] = {
            value: list[i],
            label: list[i] + '年'
          }
        }

        console.log(this.financialOption)
        console.log(this.financialType)

        getFinancialInfo({recordYear: this.financialType}).then(res => {
          var parts = []
          parts[0] = {value: (res.data.benefit / 100000000.0).toFixed(2), name: '利润', itemStyle: {color: '#00b33c'}}
          parts[1] = {value: (res.data.outcome / 100000000.0).toFixed(2), name: '支出', itemStyle: {color: '#ff1a1a'}}

          console.log(parts)

          this.financial_info.series[0].data = parts

          this.income = (res.data.income / 100000000.0).toFixed(2)

          echarts.init(document.getElementById('financial_info')).setOption(this.financial_info)
        })
      })
    },
    recordInOutEchartsInit(type) {
      getRecordInOutInfos({statisticalType: type}).then(res => {

        var recordIn = res.data.recordIn
        var recordOut = res.data.recordOut

        console.log(recordIn)
        console.log(recordOut)

        var times = []
        var outs = []
        var ins = []

        if (type == 'recent_day_total') {
          var date = new Date()

          // 减7天
          date = date.setDate(date.getDate() - 7)
          date = new Date(date)

          for (var i = 0; i < 7; i++) {

            // var y = date.getFullYear()
            // var m = date.getMonth() + 1
            // var d = date.getDate()

            times[i] = date.Format("yyyy-MM-dd")

            date = date.setDate(date.getDate() + 1)
            date = new Date(date)
          }

          console.log(times)

          for (var i = 0; i < times.length; i++) {
            console.log(recordIn)
            console.log(recordOut)
            for (var j = 0; j < recordIn.length; j++) {
              if (times[i] == recordIn[j].statisticalTime) {
                ins[i] = recordIn[j].goodsCount
                break
              }
            }

            for (var j = 0; j < recordOut.length; j++) {
              if (times[i] == recordOut[j].statisticalTime) {
                outs[i] = recordOut[j].goodsCount
                break
              }
            }

            ins[i] = ins[i] == null ? 0 : ins[i]
            outs[i] = outs[i] == null ? 0 : outs[i]
          }
        } else {

          for (var i = 0; i < recordOut.length; i++) {
            outs[i] = recordOut[i].goodsCount
            times[i] = recordOut[i].statisticalTime
            ins[i] = recordIn[i].goodsCount
          }

          console.log(times)
          console.log(outs)
          console.log(ins)

        }

        this.record_in_out.xAxis.data = times
        this.record_in_out.series[0].data = ins
        this.record_in_out.series[1].data = outs

        console.log(this.record_in_out.xAxis.data)
        console.log(this.record_in_out.series[0].data)
        console.log(this.record_in_out.series[1].data)

        echarts.init(document.getElementById('record_in_out')).setOption(this.record_in_out)
      })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 12px;
}

.el-row {
  margin-bottom: 12px;

&
:last-child {
  margin-bottom: 0;
}

}
</style>
